﻿using System;
using MediatR;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.IC;
using Casamiel.Domain;

using System.Net.Http;
using Casamiel.Common;
using Microsoft.Extensions.Options;
using System.Threading;
using System.Threading.Tasks;

namespace Casamiel.Application.Commands.MemberTicket
{
	/// <summary>
	/// 
	/// </summary>
	public sealed class GetMemberTicketGiveDetailCommandHandler:BaseCommandHandler,IRequestHandler<GetMemberTicketGiveDetailCommand, BaseResult<TicketGiveReponse>>
	{
		private readonly ICasaMielSession _session;
		private readonly IMemberTicketGiveRepository  _memberTicketGiveRepository;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="casaMielSession"></param>
		/// <param name="memberTicketGiveRepository"></param>
		/// <param name="netICService"></param>
		/// <param name="httpClientFactory"></param>
		/// <param name="settings"></param>
		public GetMemberTicketGiveDetailCommandHandler(ICasaMielSession casaMielSession, IMemberTicketGiveRepository  memberTicketGiveRepository,INetICService netICService,
			IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings) : base(netICService, httpClientFactory, settings)

		{
			_session = casaMielSession;
			_memberTicketGiveRepository = memberTicketGiveRepository;
 
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public async Task<BaseResult<TicketGiveReponse>> Handle(GetMemberTicketGiveDetailCommand request, CancellationToken cancellationToken)
		{
			if (request is null) {
				throw new ArgumentNullException(nameof(request));
			}

			var entity = await _memberTicketGiveRepository.FindAsync<ICasaMielSession>(request.ForwardCode).ConfigureAwait(false);
			if (entity != null) {
				if (entity.Status == 0 && entity.CreateTime < DateTime.Now.AddDays(-2)) {
					entity.Status = -1;
					await _memberTicketGiveRepository.UpdateAsync<ICasaMielSession>(entity).ConfigureAwait(false);
				}
				 




				var rsp = new TicketGiveReponse {
					ForwardCode = entity.ForwardCode,
					Message = entity.Message,
					State = entity.Status,
					Ticketname = entity.Ticketname
				};
				return new BaseResult<TicketGiveReponse>(rsp, 0, "");
			}
			return new BaseResult<TicketGiveReponse>(null, 999, "信息不存在");

		}
	}
}
